package com.zeny.coding.service.impl;

import com.alibaba.fastjson.JSON;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zeny.coding.constants.CourseConstants;
import com.zeny.coding.dto.PageDto;
import com.zeny.coding.dto.ResourceDto;
import com.zeny.coding.dto.UserDto;
import com.zeny.coding.entity.Resource;
import com.zeny.coding.entity.User;
import com.zeny.coding.entity.UserExample;
import com.zeny.coding.mapper.RoleMapper;
import com.zeny.coding.mapper.UserMapper;
import com.zeny.coding.service.UserService;
import com.zeny.coding.util.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * <h2>用户服务</h2>
 *
 * @Author Zeny
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;


    @Override
    public void list(PageDto<UserDto> pageDto) {
        //分页
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());
        //设置条件
        UserExample userExample = new UserExample();
        userExample.setOrderByClause("id desc");
        //查询结果
        List<User> userList = this.userMapper.selectByExample(userExample);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        //设置总条数
        pageDto.setTotal(pageInfo.getTotal());
        //封装成DTO传输
        List<UserDto> userDtoList = new ArrayList<>();
        for (User user : userList) {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user, userDto);
            userDtoList.add(userDto);
        }
        //设置记录数
        pageDto.setList(userDtoList);
    }

    @Override
    public void save(UserDto userDto) {
        //检查用户名
        User userDb = findByLoginName(userDto.getLoginName());
        if (userDb != null) {
            throw new RuntimeException(CourseConstants.USER_EXIST);
        }
        //DTO转~
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        //算法算法生成ID
        SnowFlake snowFlake = new SnowFlake(
                CourseConstants.dataCenterId,
                CourseConstants.machineId);
        user.setId(String.valueOf(snowFlake.nextId()));
        this.userMapper.insertSelective(user);
    }

    @Override
    public void update(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        this.userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public UserDto findById(String id) {
        User user = this.userMapper.selectByPrimaryKey(id);
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);
        return userDto;
    }

    @Override
    public void deleteById(String id) {
        this.userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public User findByLoginName(String loginName) {
        UserExample example = new UserExample();
        example.createCriteria().andLoginNameEqualTo(loginName);
        List<User> users = this.userMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(users)) {
            return null;
        }
        return users.get(0);
    }

    @Override
    public void resetPassword(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        this.userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public UserDto login(UserDto userDto) {
        User user = findByLoginName(userDto.getLoginName());
        if (user == null) {
            //用户不存在
            log.info("用户:{} 不存在", userDto);
            throw new RuntimeException(CourseConstants.USERNAME_PASSWORD_ERROR);
        } else {
            if (user.getPassword().equals(userDto.getPassword())) {
                //登录成功
                BeanUtils.copyProperties(user, userDto);
                userDto.setPassword(null);
                setAuth(userDto);
                return userDto;
            } else {
                //密码错误
                log.info("用户密码错误:{} 不存在", userDto);
                throw new RuntimeException(CourseConstants.USERNAME_PASSWORD_ERROR);
            }
        }
    }

    @Override
    public List<ResourceDto> findResourcesByUserId(String userId) {
        List<Resource> resources = this.userMapper.findResourcesByUserId(userId);
        List<ResourceDto> resourceDtos = new ArrayList<>();
        for (Resource resource : resources) {
            ResourceDto resourceDto = new ResourceDto();
            BeanUtils.copyProperties(resource, resourceDto);
            resourceDtos.add(resourceDto);
        }
        return resourceDtos;
    }

    private void setAuth(UserDto userDto){
        List<ResourceDto> resourceDtoList = findResourcesByUserId(userDto.getId());
        userDto.setResources(resourceDtoList);
        //整理所有权限请求，用于接口拦截
        HashSet<String> requestSet = new HashSet<>();
        if (!CollectionUtils.isEmpty(resourceDtoList)) {
            for (ResourceDto resourceDto : resourceDtoList) {
                String arrStr = resourceDto.getRequest();
                List<String> requestList = JSON.parseArray(arrStr, String.class);
                if (!CollectionUtils.isEmpty(requestList)) {
                    requestSet.addAll(requestList);
                }
            }
        }
        log.info("设置用户权限,整理权限请求: {}", requestSet);
        userDto.setRequests(requestSet);

    }
}
